$(function() {
    $('#orderNotice input[name="publication[]"]:last')
        .parents('p')
            .after('<p id="totalPurchase" class="checkbox">Total: <span class="price">$0.00</span></p>');
    $('#orderNotice input[name="publication[]"]')
        .click(function () {
            var total = 0;
            $('#orderNotice input[name="publication[]"]').each(function () {
                var price = $('span', $(this).parent()).html();
                value = parseFloat(price.match(/[\d\.]+/));
                if (this.checked) {
                    total += value;
                }
            });
            $('#totalPurchase span')
                .html('$'+total.toFixed(2));
        });
    function publicationIsChecked() {
        return $('#orderNotice input[name="publication[]"]:checked').length > 0;
    }
    function emailHasValue() {
        return this.value > '';
    }
    function confirmEmailMatches() {
        return $('#orderNotice input[name="email"]').val() === $(this).val();
    }
    function hideErrorWhen(condition) {
        return function () {
            $error = $(this).parent('p').prev();
            if ($error.hasClass('error')) {
                if (condition.call(this) === true) {
                    $error.hide('slow');
                } else {
                    $error.show('slow');
                }
            }
        };
    }
    $('#orderNotice input[name="publication[]"]').click(hideErrorWhen(publicationIsChecked));
    $('#orderNotice input[name="email"]').change(hideErrorWhen(emailHasValue));
    $('#orderNotice input[name="confirmEmail"]').change(hideErrorWhen(confirmEmailMatches));
});